import json

import requests

from futil import read_file_lines, write_json


def check_host(host: str):
    try:
        resp = requests.get(f'https://{host}/v2/namespaces/library/repositories/hello-world/tags', verify=False,timeout=5)
        print(resp.url)
        status_code=resp.status_code
        print(resp.status_code)
        print(resp.text)
        return status_code<500
    except Exception as e:
        print(e)
        return False

def validate_mirrors():
    # check_host('docker.io')
    valids = []
    for line in read_file_lines('possibledockermirrows.txt'):
        host = line.strip()
        print(host)
        if check_host(host):
            valids.append(host)
    print('-'*20)
    for h in valids:
        print(h)
    # check_host('registry.hub.docker.com')

def gen_mirrow_cfg():
    lines = read_file_lines('possibledockermirrows.txt')
    d = {
        "registry-mirrors":[
            f"https://{h.strip()}"
                            for h in lines]
    }
    write_json(d,'docker.mirrors.json')

if __name__ == '__main__':
    gen_mirrow_cfg()